import { launch } from "puppeteer";
import { readFile } from "fs/promises";
import { homedir } from "os";
import { join } from "path";

const SUBSCRIBES_FILE = join(homedir(), ".config/youtube/subscribes.txt");

export async function getUrls() {
  const urlsStr = await readFile(SUBSCRIBES_FILE, {
    encoding: "utf8",
  });
  return urlsStr.split("\n").filter((item) => Boolean(item));
}

export async function getVideosUrl(url: string) {
  const browser = await launch({ headless: true });
  const page = await browser.newPage();
  await page.goto(url);
  await page.waitForNetworkIdle();

  const res = await page.evaluate(() => {
    const divs = document.querySelectorAll(
      "div.pure-g>div.pure-u-1.pure-u-md-1-4>div.h-box"
    );
    return Array.from(divs).map((div: Element) => {
      const container = div as HTMLDivElement;
      const link = container.querySelector("a");
      const videoUrl = link?.href;
      const p = link?.querySelector("p[dir]")?.textContent;

      return {
        videoUrl,
        title: p,
      };
    });
  });

  browser.close();

  return res;
}

export async function getChannelName(url: string) {
  const browser = await launch({ headless: true });
  const page = await browser.newPage();
  await page.goto(url);
  await page.waitForNetworkIdle();

  const res = await page.evaluate(() => {
    return document.querySelector(".channel-profile>span")?.textContent;
  });

  await browser.close();

  return res;
}
